package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "微信登录接口")
public class wxUser {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;



    //用户登录接口
    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录接口");
        if (userLoginDTO == null || userLoginDTO.getCode() == null) {
            return Result.error("参数不能为空");
        }

        //验证登录代码code，获取openid等信息，创建用户对象

        User user =userService.getOpenId(userLoginDTO);

        //生成token 定义秘钥、过期时间、签名
        Map<String, Object> clames = new HashMap<>();
        clames.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), clames);
//        String token= JwtUtil.createToekn(user.getId(), jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl());
        //拼接UserLoginVO对象并返回
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(user.getOpenid());
        userLoginVO.setToken(token);

        return Result.success(userLoginVO);
    }

}
